package cn.net.csit.platform_cloud.basicmodel.service.impl;


import cn.net.csit.platform_cloud.basicmodel.domain.BasicObjDictionaryDomain;
import cn.net.csit.platform_cloud.basicmodel.domain.BasicObjPropertyRelationDomain;
import cn.net.csit.platform_cloud.basicmodel.domain.BasicPropertyDictionaryDomain;
import cn.net.csit.platform_cloud.basicmodel.mapper.BasicObjPropertyRelationDomainMapper;
import cn.net.csit.platform_cloud.basicmodel.service.IBackupDataService;
import cn.net.csit.platform_cloud.basicmodel.service.IBasicObjectDictionaryService;
import cn.net.csit.platform_cloud.basicmodel.service.IBasicObjectPropertyRelationService;
import cn.net.csit.platform_cloud.basicmodel.service.IBasicPropertyDictionaryService;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName:
 * @Author:yanwenjuan
 * @Date:2019/4/811:00
 * @Description:
 */
@Service
public class BasicObjectPropertyRelationServiceImpl implements IBasicObjectPropertyRelationService {
   @Autowired
   private BasicObjPropertyRelationDomainMapper mapper;
    @Autowired
    IBackupDataService backupDataService;
    @Autowired
    IBasicPropertyDictionaryService basicPropertyDictionaryService;
    @Autowired
    IBasicObjectDictionaryService iBasicObjectDictionaryService;
    @Autowired
    IBasicObjectPropertyRelationService iBasicObjectPropertyRelationService;
    @Autowired
    RestTemplate restTemplate;//接口调用的封装
    @Value("${target.host1}")//外部接口地址
    private String targetHost1;
    @Value("${target.host2}")//外部接口地址
    private String targetHost2;
    //0.所有对象列表展示--分页，有条件（对象名称）
    @Override
    public List<Map<String, String>> getAll(Map<String, String> map) {
        List<Map<String, String>> result=new ArrayList<>();
        String where="where  1=1 ";
        if(null!=map&null!=map.get("uuid")){
            where =where+" and bod_t0.uuid="+map.get("uuid");
        }
        if(null!=map&null!=map.get("obj_name")){
            where =where+" and bod_t0.obj_name="+map.get("obj_name");
        }
        StringBuilder sb=new StringBuilder();
        sb.append(" SELECT bod_t0.*,temp.obj_name parent_obj_name ");
        sb.append(" FROM basic_obj_dictionary bod_t0");
        sb.append(" LEFT JOIN (");
        sb.append(" SELECT uuid,obj_name FROM basic_obj_dictionary");
        sb.append("  ) temp ON bod_t0.obj_parent_uuid = temp.uuid ");
        sb.append(" "+where);
        result=backupDataService.customQueryItem(sb);
        return result;
    }
    //1.所有属性列表展示--不分页，有条件（根据属性名称，属性组名称查询（包含关系），查询属性列表集合）
    @Override
    public List<BasicPropertyDictionaryDomain> getAllProp(Map<String, String> map) {
        List<BasicPropertyDictionaryDomain> domainList=basicPropertyDictionaryService.getAll(map);
        return domainList;
    }
    //2.根据对象uuid查询属性列表配置情况
    @Override
    public Map<String,String> getAllPropByUuid(Map<String, String> map) {
        //根据对象uuid查询对象关系表的属性的uuid集合
        Map<String,String> result = new HashMap<>();
        String prop_text="";
        if(null!=map&null!=map.get("uuid")){
            prop_text= getAllPropByUuid(map.get("uuid"));
        }
        //根据对象uuid获取一条记录
        BasicObjDictionaryDomain domain=iBasicObjectDictionaryService.selectByPrimaryKey(map.get("uuid"));
        if(null!=domain){
            result.put("uuid",domain.getUuid());
            result.put("objCode",domain.getObjCode());
            result.put("objName",domain.getObjName());
            result.put("author",domain.getAuthor());
            result.put("objDesc",domain.getObjDesc());
            result.put("objParentUuid",domain.getObjParentUuid());
            result.put("organType",domain.getOrganType());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            if(null!=domain.getCreateTime()){
                result.put("createTime",sdf.format(domain.getCreateTime()));
            }else{
                result.put("createTime","");
            }
            result.put("propText",prop_text);
        }

        return result;
    }
    //2-1,根据对象uuid获取属性集合
    @Override
    public String getAllPropByUuid(String obj_uuid) {
        //根据对象uuid查询对象关系表的属性的uuid集合
        String where="where  1=1 ";
        if(null!=obj_uuid&&!obj_uuid.equals("")){
            where =where+" and obj_uuid='"+obj_uuid+"'";
        }
        StringBuilder sb=new StringBuilder();
        sb.append(" SELECT prop_uuid");
        sb.append(" FROM basic_obj_property_relation ");
        sb.append(" "+where);
        List<Map<String,String>>  list=backupDataService.customQueryItem(sb);
        String prop_text="";
        if(null!=list&&list.size()>0){
            for(int i=0;i<list.size();i++){
                Map<String,String> m= list.get(i);
                if(null!=m.get("prop_uuid")){
                    String temp=list.get(i).get("prop_uuid")+",";
                    prop_text=prop_text+temp;
                }
            }
            //去掉末尾的逗号
            prop_text=prop_text.substring(0,prop_text.length()-1);
        }

        return prop_text;
    }
    //3.根据对象uuid修改属性列表配置情况（增加，或减少关系）
    @Override
    public Map<String, String> updateAllPropByUuid(Map<String, String> map) {
        Map<String,String> result = new HashMap<>();
        //根据对象uuid查询一条对象记录
        BasicObjDictionaryDomain domain=iBasicObjectDictionaryService.selectByPrimaryKey(map.get("uuid"));
        //根据对象uuid获取属性集合--旧
        String old_prop_uuids=getAllPropByUuid(map.get("uuid"));
        List<Map<String, String>> newPropExtList = getPropExtList(map.get("prop_uuids"));
        List<Map<String, String>> oldPropExtList = getPropExtList(old_prop_uuids);
        //根据属性动态创建字段
        createInstanceField(domain,newPropExtList,oldPropExtList);
        //如果新集合里的属性uuid,不在旧集合集合中，则将这部分集合放到一起，然后执行插入关系操作
        result=getAllPropByUuid(map);
        return result;
    }

    @Override
    public void insert(BasicObjPropertyRelationDomain mesPropRelation) {
        mapper.insert(mesPropRelation);
    }

    private void createInstanceField(BasicObjDictionaryDomain domain, List<Map<String,String>> newPropExtList, List<Map<String,String>> oldPropExtList)  {
        String uuid = domain.getUuid();
        String old_prop_uuids=getAllPropByUuid(uuid);
        if(null !=old_prop_uuids ){
            Map<String,Map<String, String>> newPropExtMap = new HashMap<>();
            Map<String,Map<String, String>> oldPropExtMap = new HashMap<>();
            if (null != newPropExtList && newPropExtList.size() > 0) {
                for (int i = 0; i < newPropExtList.size(); i++) {
                    newPropExtMap.put(newPropExtList.get(i).get("uuid"), newPropExtList.get(i));
                }
            }
            if (null != oldPropExtList && oldPropExtList.size() > 0) {
                for (int j = 0; j < oldPropExtList.size(); j++) {
                    oldPropExtMap.put(oldPropExtList.get(j).get("uuid"), oldPropExtList.get(j));
                }
            }
            //定义删除列集合
            Map<String,String> deleteProps=new HashMap<>();
            for (String key : oldPropExtMap.keySet()) {
                //如果旧集合里的属性uuid,不在新属性集合中，则将这部分旧集合放到一起，然后执行删除关系
                if(!newPropExtMap.containsKey(key)){
                    StringBuilder deleteSql = new StringBuilder();
                    deleteSql.append("delete from basic_obj_property_relation where obj_uuid = '"+uuid+"' and prop_uuid = '"+key+"'") ;
                   System.out.println("deleteSql"+deleteSql.toString());
                    //删除关系
                    backupDataService.customQueryItem(deleteSql);
                    //删除列
                    deleteProps.put(oldPropExtMap.get(key).get("prop_code"),oldPropExtMap.get(key).get("prop_name"));

                }
            }
            if(deleteProps.size()>0){
                //删除实例表扩展属性字段
                Map<String,Object> map =new HashMap<>();
                Map<String,Object> addMap=new HashMap<>();
                map.put("objCode",domain.getUuid());
                map.put("extendAttr",deleteProps);
                addMap.put("planTemplate",map);
                //此处添加接口代码，发送删除列请求
                String url = targetHost2;
                Map<String,Object> result =  getPlanTemps(addMap,url);
            }

            //定义增加列集合
            Map<String,String> addProps=new HashMap<>();
            for (String key : newPropExtMap.keySet()) {
                if(!oldPropExtMap.containsKey(key)){

                    //保存属性实体对应关系表
                    BasicObjPropertyRelationDomain mesPropRelation = new BasicObjPropertyRelationDomain();
                    mesPropRelation.setObjName(domain.getObjName());
                    mesPropRelation.setObjUuid(domain.getUuid());
                    mesPropRelation.setPropUuid(key);
                    iBasicObjectPropertyRelationService.insert(mesPropRelation);
                    //获得需要添加的字段list
                    addProps.put(newPropExtMap.get(key).get("prop_code"),newPropExtMap.get(key).get("prop_name"));
                }
            }
            //添加实例表字段

            if(addProps.size()>0){
                Map<String,Object> map =new HashMap<>();
                Map<String,Object> addMap=new HashMap<>();
                map.put("objCode",domain.getUuid());
                map.put("extendAttr",addProps);
                addMap.put("planTemplate",map);
                //此处添加接口代码，发送增加列请求
                String url = targetHost1;
                Map<String,Object> result =  getPlanTemps(addMap,url);
                }
            }


        }
    @Override
    public void deleteByObjUuid(String obj_uuid){
        StringBuilder deleteSql=new StringBuilder();
        deleteSql.append("delete from basic_obj_property_relation where obj_uuid = '"+ obj_uuid +"'") ;
        //删除关系
        backupDataService.customQueryItem(deleteSql);
    }
    @Override
    public void deleteByPropUuid(String prop_uuid){
        StringBuilder deleteSql=new StringBuilder();
        deleteSql.append("delete from basic_obj_property_relation where prop_uuid = '"+ prop_uuid +"'") ;
        //删除关系
        backupDataService.customQueryItem(deleteSql);
    }

    private List<Map<String,String>> getPropExtList(String prop_uuids) {
        if(null != prop_uuids && !"".equals(prop_uuids)){
            //转换参数 以逗号分割，两侧加单引号，将","替换为"','"
            String temp="";
            if(prop_uuids.contains(",")){
                temp=prop_uuids.replace(",","','");
            }else{
                temp=prop_uuids;
            }

            StringBuilder sb=new StringBuilder();
            sb.append(" select * from basic_property_dictionary where uuid in ");
            sb.append(" ('"+temp+"')");
            System.out.println("sql"+sb.toString());
            List<Map<String,String>> propList = backupDataService.customQueryItem(sb);
            return propList;
        }
        return new ArrayList<>();
    }
    private  Map<String,Object> getPlanTemps( Map<String,Object> map,String url ) {
        Map<String,Object> result = new  JSONObject();
        ResponseEntity<JSONObject> forEntity = restTemplate.getForEntity(url, JSONObject.class,map);
        if(!StringUtils.isEmpty(forEntity)&&forEntity.getStatusCode().value()==200){
            result = (Map<String,Object>)JSONObject.toJSON(forEntity.getBody().get("data"));
        }
        return result;
    }

}
